package com.lezhi.socialgram.api.sys;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.sys.TelNumSignInMapper;
import com.lezhi.socialgram.model.sys.ResetPwdUser;
import com.lezhi.socialgram.model.sys.TelNumSignInUser;
import com.lezhi.socialgram.model.sys.UpdatePwdUser;
import com.lezhi.socialgram.service.sys.PasswordService;
import com.lezhi.socialgram.service.sys.SMSVeriService;
import com.lezhi.socialgram.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by daizhen on 2017/3/23.
 * 密码 api 修改密码、找回密码
 */
@RestController
public class PasswordApi {

    private static final Logger logger = LoggerFactory.getLogger(PasswordApi.class);

    @Autowired
    PasswordService passwordService;

    @Autowired
    SMSVeriService smsVeriService;

    @Autowired
    TelNumSignInMapper telNumSignInMapper;

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody @Valid UpdatePwdUser updatePwdUser, BindingResult bindingResult) {
        ValidUtils.valid(logger, bindingResult);
        return passwordService.updatePassword(updatePwdUser);
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody @Valid ResetPwdUser resetPwdUser, BindingResult bindingResult) {
        ValidUtils.valid(logger, bindingResult);
        try {
            Result result = smsVeriService.verifySMSCode(resetPwdUser.getTelNum(), resetPwdUser.getVerifyCode());
            if (!result.getCode().equals("0"))
                return result;
            UpdatePwdUser updatePwdUser = new UpdatePwdUser();
            TelNumSignInUser telNumSignInUser = new TelNumSignInUser();
            telNumSignInUser.setTelNum(resetPwdUser.getTelNum());
            String indexByTel = XUtil.getTableNameIndexByTel(telNumSignInUser.getTelNum());
            String table = Param.T_USER_TEL_NUM_INDEX_TABLE_PREFIX + indexByTel;
            telNumSignInUser.setTable(table);
            TelNumSignInUser user = telNumSignInMapper.getUserId(telNumSignInUser);
            updatePwdUser.setUserId(user.getUserId());
            updatePwdUser.setNewPwd(resetPwdUser.getPassword());
            return passwordService.updatePassword(updatePwdUser);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

}
